﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Text;
using CharacterTrailLibrary.Exceptions;
using CharacterTrailLibrary.Factory;
using CharacterTrailLibrary.Interface;
using CharacterTrailLibrary.Persist.BLL.Model;
using CharacterTrailLibrary.Security;

namespace CharacterTrailLibrary.Impl
{
    public class ExcelImportorNew : IExcelImportor
    {
        public const string TableName = "BOM数据$";
        public System.Data.DataTable GetDataTable(string fileName)
        {
            DataTable excelTable = null;
            var ds = new DataSet();

            var conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";" + "Extended Properties=Excel 8.0;");
            conn.Open();
            //var schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            //string tableName = schemaTable.Rows[0][2].ToString().Trim();//获取 Excel 的表名，默认值是sheet1
            var strSql = "select * from [" + TableName + "]";
            var myData = new OleDbDataAdapter(strSql, conn);
            myData.Fill(ds, TableName);

            conn.Close();

            excelTable = ds.Tables[TableName];

            var dataRows = new List<DataRow>();

            foreach (DataRow row in excelTable.Rows)
            {
                if (String.IsNullOrEmpty(row["产品代码"].ToString()))
                {
                    dataRows.Add(row);
                }
            }
            foreach (DataRow row in dataRows)
            {
                excelTable.Rows.Remove(row);
            }
            excelTable.Columns.Add("ProductItemId", typeof(Int32));
            excelTable.Columns.Add("MaterialItemId", typeof(Int32));
            excelTable.AcceptChanges();



            DataTable returnTable = excelTable.Clone();
            IStaticDataQuerier staticDataQuerier = InstanceFactory.GetStaticDataQuerier();

            var proList = staticDataQuerier.GetProcedureModelList();

            foreach (DataRow row in excelTable.Rows)
            {
                TProcedureModel procedureModel = null;
                if (!ProcedureInList(row["工序号"].ToString().Trim(), proList, out procedureModel))
                {
                    throw new AppException(string.Format("工序号{0}没有维护到系统中！", row["工序号"].ToString().Trim()));
                }

                //从数据库中找产品/物料代码
                var iCItemModelParent = staticDataQuerier.GetVIcItemQueryModel(row["产品代码"].ToString().Trim());
                if (iCItemModelParent == null)
                {
                    throw new AppException(String.Format("产品/物料代码{0}在系统中没有维护！", row["产品代码"].ToString().Trim()));
                }

                var iCItemModelChild = staticDataQuerier.GetVIcItemQueryModel(row["物料代码"].ToString().Trim());
                if (iCItemModelChild == null)
                {
                    throw new AppException(String.Format("产品/物料代码{0}在系统中没有维护！", row["物料代码"].ToString().Trim()));
                }

                DataRow dr = returnTable.NewRow();
                dr.ItemArray = row.ItemArray;
                dr["ProductItemId"] = iCItemModelParent.FItemId;
                dr["产品名称"] = iCItemModelParent.FName;

                dr["MaterialItemId"] = iCItemModelChild.FItemId;
                dr["物料名称"] = iCItemModelChild.FName;
                returnTable.Rows.Add(dr);
            }
            returnTable.AcceptChanges();
            return returnTable;
        }

        private bool ProcedureInList(string procedureNo, List<TProcedureModel> list, out TProcedureModel proModel)
        {
            proModel = null;
            foreach (var procedureModel in list)
            {
                if (procedureModel.ProcedureNo == procedureNo)
                {
                    proModel = procedureModel;
                    return true;
                }
            }
            return false;
        }

        public void ImportToDb(System.Data.DataTable dataTable)
        {
            IStaticDataQuerier staticDataQuerier = Factory.InstanceFactory.GetStaticDataQuerier();
            var proList = staticDataQuerier.GetProcedureModelList();

            IBom bomImpl = Factory.InstanceFactory.GetBom();
            foreach (DataRow dr in dataTable.Rows)
            {
                var bomMainModel = new TBomMainModel();
                bomMainModel.ProductItemId = int.Parse(dr["ProductItemId"].ToString());
                bomMainModel.ProductItemNumber = dr["产品代码"].ToString().Trim();
                bomMainModel.ProductItemName = dr["产品名称"].ToString();
                bomMainModel.ProductVersion = "1";//???
                bomMainModel.CheckStatus = 0;
                bomMainModel.ImportStatus = 1;
                bomMainModel.ImportDate = DateTime.Now;
                bomMainModel.ImportId = UserSession.CurrentUser.UserId;
                //bomMainModel.ExtChar1 = UserSession.CurrentUser.UserName;

                TProcedureModel procedureModel = null;
                if (!ProcedureInList(dr["工序号"].ToString().Trim(), proList, out procedureModel))
                {
                    throw new AppException(string.Format("工序号{0}没有维护到系统中！", dr["工序号"].ToString().Trim()));
                }
                var bomEntryModel = new TBomEntryModel();
                bomEntryModel.ProcedureNo = procedureModel.ProcedureNo;
                bomEntryModel.ProcedureName = procedureModel.ProcedureName;
                bomEntryModel.ProductItemId = int.Parse(dr["ProductItemId"].ToString());
                bomEntryModel.ProductItemNumber = dr["产品代码"].ToString().Trim();
                bomEntryModel.ProductItemName = dr["产品名称"].ToString();
                bomEntryModel.ProductVersion = "1";//?????
                bomEntryModel.ImportId = UserSession.CurrentUser.UserId;
                //bomEntryModel.ExtChar1 = UserSession.CurrentUser.UserName;
                bomEntryModel.ImportStatus = 1;
                bomEntryModel.ImportDate = DateTime.Now;
                bomEntryModel.MaterialItemId = int.Parse(dr["MaterialItemId"].ToString());
                bomEntryModel.MaterialItemNumber = dr["物料代码"].ToString().Trim();
                bomEntryModel.MaterialItemName = dr["物料名称"].ToString();

                decimal number = 0;
                if(decimal.TryParse(dr["数量"].ToString(),out number))
                {
                    bomEntryModel.Qty = number;
                }
                else
                {
                    throw new Exception("数量字段不能为空！");
                }

                try
                {
                    bomImpl.SaveBom(bomMainModel, bomEntryModel);
                }
                catch (Exception exception)
                {
                    if (exception.Message.Contains("已经包括了物料"))
                    {
                        //如果是物料已经存在，则可以不抛异常！
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
    }
}
